package com.south.base.test.arithmetic;

import java.util.Iterator;

/**
 * 给定一个迭代器类的接口，接口包含两个方法： next() 和 hasNext()。
 * 设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。
 *
 * @author Administrator
 * @date 2019/5/28 10:52
 */
public class PeekingIterator implements Iterator<Integer> {

    private Iterator<Integer> iterator;
    private Integer next = null;
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        this.iterator = iterator;
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        if (next == null) {
            return next = iterator.next();
        }
        return next;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
    @Override
    public Integer next() {
        if (next != null) {
            Integer next = this.next;
            this.next = null;
            return next;
        }
        return iterator.next();
    }

    @Override
    public boolean hasNext() {
        return next != null || iterator.hasNext();
    }
}
